/**
 *@Time    : 2021/11/14 14:19
 *@Author  : Shuai Jhou
 *@File    : UserService
 *@Software: GoLand
 */

package services

import (
	"context"
	"time"
)

type UserService struct {
}

// GetUserScore  普通方法
func (s *UserService) GetUserScore(ctx context.Context, userScoreRequest *UserScoreRequest) (*UserScoreResponse,
	error) {
	var score int32 = 88
	users := make([]*UserInfo, 0)
	for _, user := range userScoreRequest.Users {
		user.UserScore = score
		score++
		users = append(users, user)
	}
	return &UserScoreResponse{Users: users}, nil
}

func (s *UserService) GetUserScoreByServerStream(userScoreRequest *UserScoreRequest,
	stream UserService_GetUserScoreByServerStreamServer) error {
	var score int32 = 88
	users := make([]*UserInfo, 0)
	for index, user := range userScoreRequest.Users {
		user.UserScore = score
		score++
		users = append(users, user)
		if (index+1)%2 == 0 && index > 0 {
			err := stream.Send(&UserScoreResponse{Users: users})
			if err != nil {
				return err
			}
			users = (users)[0:0]
		}
		// 模拟耗时操作
		time.Sleep(1 * time.Second)
	}
	if len(users) > 0 {
		err := stream.Send(&UserScoreResponse{Users: users})
		if err != nil {
			return err
		}
	}
	return nil
}
